package cn.com.dcsgo.service.impl;

import cn.com.dcsgo.dto.MemberInfoDTO;
import cn.com.dcsgo.dto.PageDTO;
import cn.com.dcsgo.dto.ProdCommQueryDTO;
import cn.com.dcsgo.dto.ReviewReplyProdCommDTO;
import cn.com.dcsgo.feign.MemberFeignClient;
import cn.com.dcsgo.utils.AuthUtil;
import cn.com.dcsgo.vo.ProdCommOverviewVO;
import cn.com.dcsgo.vo.ProdCommVO;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.com.dcsgo.domain.ProdComm;
import cn.com.dcsgo.service.ProdCommService;
import cn.com.dcsgo.mapper.ProdCommMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 针对表【prod_comm(商品评论)】的数据库操作Service实现
 *
 * @author Dcsgo
 * @since 2025-10-14 08:45:29
 */
@Service
public class ProdCommServiceImpl extends ServiceImpl<ProdCommMapper, ProdComm>
        implements ProdCommService {
    @Resource
    private MemberFeignClient memberFeignClient;

    @Override
    public Page<ProdComm> getPage(PageDTO pageDTO, ProdCommQueryDTO prodCommQueryDTO) {
        Page<ProdComm> page = new Page<>(pageDTO.getCurrent(), pageDTO.getSize());
        // 非超级店铺只能看到自己店铺下的商品的评论
        Long shopId = AuthUtil.getShopId();
        return baseMapper.selectPage(page,
                new LambdaQueryWrapper<ProdComm>()
                        .eq(shopId == null || !shopId.equals(1L), ProdComm::getShopId, shopId)
                        .eq(prodCommQueryDTO.getStatus() != null, ProdComm::getStatus, prodCommQueryDTO.getStatus())
                        .like(StringUtils.hasText(prodCommQueryDTO.getProdName()), ProdComm::getProdName, prodCommQueryDTO.getProdName())
        );
    }

    @Override
    public boolean reviewReplyProdComm(ReviewReplyProdCommDTO reviewReplyProdCommDTO) {
        ProdComm updateData = new ProdComm();
        BeanUtil.copyProperties(reviewReplyProdCommDTO, updateData);
        updateData.setReplyTime(new Date());
        updateData.setReplySts(1);
        return this.updateById(updateData);
    }

    @Override
    public ProdCommOverviewVO getProdCommOverviewVO(Long prodId) {
        //TODO: 使用统计表（prod_comm_stat）查询，而不是每次都查询一次评论表
        ProdCommOverviewVO overviewVO = baseMapper.selectProdCommStatInfoByProdId(prodId);
        if (overviewVO.getAllCount() > 0) {
            Long goodCount = overviewVO.getGoodCount();
            Long allCount = overviewVO.getAllCount();
            int goodLv = (int) Math.ceil(goodCount * 100.0 / allCount);
            overviewVO.setGoodLv(goodLv);
        }
        return overviewVO;
    }

    @Override
    public Page<ProdCommVO> getProdCommVOPage(Long prodId, Integer evaluate, PageDTO pageDTO) {
        Page<ProdCommVO> result = new Page<>(pageDTO.getCurrent(), pageDTO.getSize());
        Page<ProdComm> prodCommPage = new Page<>(pageDTO.getCurrent(), pageDTO.getSize());
        page(prodCommPage,
                new LambdaQueryWrapper<ProdComm>()
                        .eq(ProdComm::getStatus, 1)
                        .eq(evaluate != -1 && evaluate != 3, ProdComm::getEvaluate, evaluate)
                        .isNotNull(evaluate == 3, ProdComm::getPics)
                        .eq(ProdComm::getProdId, prodId)
        );
        List<ProdComm> prodCommList = prodCommPage.getRecords();
        result.setRecords(
                prodCommList.stream().map(prodComm -> {
                    ProdCommVO prodCommVO = new ProdCommVO();
                    BeanUtil.copyProperties(prodComm, prodCommVO);
                    return prodCommVO;
                }).toList()
        );
        if (!prodCommList.isEmpty()) {
            // 获取并设置评论关联的会员信息（昵称和头像）
            Set<String> openidSet = prodCommList.stream().map(ProdComm::getOpenId).collect(Collectors.toSet());
            List<MemberInfoDTO> memberInfoList = memberFeignClient.findMemberNickNameAndPicByOpenIds(openidSet);
            Map<String, MemberInfoDTO> memberMap = memberInfoList.stream().collect(Collectors.toMap(MemberInfoDTO::getOpenId, memberInfo -> memberInfo));
            result.getRecords().forEach(prodCommVO -> {
                MemberInfoDTO memberInfoDTO = memberMap.get(prodCommVO.getOpenId());
                if (prodCommVO.getIsAnonymous() == 1) {
                    // 匿名评论，隐藏用户名和头像
                    prodCommVO.setNickName("匿名用户");
                    prodCommVO.setPic("https://dcsgo-mall.oss-cn-shanghai.aliyuncs.com/2025/11/06/%E5%8C%BF%E5%90%8D%E5%A4%B4%E5%83%8F.png");
                } else {
                    // 正常评论，解码数据库中的用户名，设置头像
                    if (memberInfoDTO != null) {
                        prodCommVO.setNickName(URLDecoder.decode(memberInfoDTO.getNickName(), StandardCharsets.UTF_8));
                        prodCommVO.setPic(memberInfoDTO.getPic());
                    }
                }
            });
        }
        result.setTotal(prodCommPage.getTotal());
        result.setPages(prodCommPage.getPages());
        return result;
    }
}




